<?php

namespace island\models;

use Yii;
use yii\data\Pagination;
use Tencentyun\ImageProcess;
use Tencentyun\ImageV2;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "t_spu_shop".
 *
 * @property integer $SpuShopId
 * @property string $SpuId
 * @property string $SpuPriceType
 * @property integer $BranchId
 * @property string $SpuName
 * @property integer $ShowPrice
 * @property integer $ShowMemberPrice
 * @property string $ImgUrl
 * @property integer $ReferencePrice
 * @property string $OnDate
 * @property string $OffDate
 * @property integer $ShopStatus
 * @property integer $HomeStatus
 * @property integer $SpuWeight
 * @property integer $ExpressPrice
 * @property integer $SpuDetailType
 * @property string $Reserv
 * @property string $WorkerId
 * @property string $SpuDetail
 */
class TSpuShop extends \yii\db\ActiveRecord
{
    //上架
    const STATUS_ONLINE = 1;
    //下架
    CONST STATUS_OFFLINE = 0;

    //默认全支持
    const TRANSACTION_DEFAULT = 0;
    //只支持快递
    const TRANSACTION_EXPRESS = 1;
    //只支持送货上门
    const TRANSACTION_DELIVERY = 2;
    //只支持门店自取
    const TRANSACTION_SELF_TAKE = 3;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 't_spu_shop';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['SpuId', 'SpuName'], 'required'],
            [['BranchId', 'ShowPrice', 'ShowMemberPrice', 'ReferencePrice', 'ShopStatus', 'HomeStatus',
                'SpuWeight', 'CategoryId', 'CategoryIdSub', 'CategoryIdTre', 'ExpressPrice', 'SpuPriceType'], 'integer'],
            [['OnDate', 'OffDate'], 'safe'],
            [['SpuId', 'WorkerId'], 'string', 'max' => 40],
            [['SpuName', 'Reserv'], 'string', 'max' => 1024],
            [['ImgUrl', 'SpuVector'], 'string', 'max' => 9216],
            [['SpuId', 'BranchId'], 'unique', 'targetAttribute' => ['SpuId', 'BranchId'], 'message' => 'The combination of 商品ID and 分店id，微商城店店为101 has already been taken.'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'SpuShopId' => '微商城商品池列表id',
            'SpuId' => '商品ID',
            'SpuPriceType' => '商品spu价格| 0-普通价格，1-特价商品，2-临时调价',
            'BranchId' => '分店id，微商城店店为101',
            'SpuName' => '商品名称',
            'SpuVector' => '商品属性维度及可选值',
            'ShowPrice' => '商品展示价格，如果各sku价格不同则展示为最低价。如相同则展示唯一价格。 例如 35~50元显示为35元， 或45元',
            'ShowMemberPrice' => '展示商品会员价格',
            'ImgUrl' => '图片url地址',
            'ReferencePrice' => '参考价格',
            'OnDate' => '上架时间',
            'OffDate' => '下架时间',
            'ShopStatus' => '商品状态 1 上架  0 下架',
            'HomeStatus' => '是否显示在首页  1显示首页  0 非首页',
            'CategoryId' => '一级分类',
            'CategoryIdSub' => '二级分类',
            'CategoryIdTre' => '三级分类',
            'SpuWeight' => '商品展示权重。值越高的越优先展示',
            'SpuDetailType' => '0 图片  1 文字',
            'TransactionMeans' => '交易方式 0-无限制 1-仅支持快递物流 2-仅支持送货上门 3-仅门店取货',
            'ExpressPrice' => '快递费 单位分',
            'SpuDetail' => '商品图文详情。如果是图片则存多图url json',
            'Reserv' => '备注',
            'WorkerId' => '工作人员id',
        ];
    }

    //图片url列表
    public function getImgUrlList()
    {
        $list = $this->ImgUrl ? json_decode($this->ImgUrl, true) : [];
        return is_array($list) ? $list : [$list];
    }

    //获取用于列表显示的产品图
    public function getCoverImg()
    {
        $imgList = json_decode($this->ImgUrl, true);
        return is_array($imgList) ? array_shift($imgList) : $imgList;
    }

    //格式化的价格
    public function getFormatPrice()
    {
        return sprintf("%.2f", $this->ShowPrice / 100);
    }

    public function getFormatMemberPrice()
    {
//        return 100;
        return sprintf("%.2f", $this->ShowMemberPrice / 100);
    }

    public function getFormatExpress()
    {
        return sprintf("%.2f", $this->ExpressPrice / 100);
    }

    //启用缓存存储所有参与促销的商品
    public function getActivity($branchid)
    {
        if (!$branchid) {
            return false;
        }
        $session = Yii::$app->session;
        $userid = $session['userid'];
        if ($userid && TUserInfo::findOne($userid)) {
            $level = TScoreLevel::findOne($userid);
            $userlevel = $level ? $level->Userlevel : 0;
        } else {
            $userlevel = 0;
        }
        $today = date("w");
        $todays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        $cache = Yii::$app->cache;
        $active = [];
        if (!$cache->get('active' . $branchid)) {
            //临时促销优先，周期促销往后
            $data = date('Y-m-d', time());
            $time = date('H:i:s', time());
            $condition = ['ActivityStatus' => TActivitySalesPromotion::Activity_Status_Begin,
                'TimeType' => TActivitySalesPromotion::TimeType_Temporary];
            $condition2 = " ActivityBeginDate <= '$data' and ActivityEndDate >='$data' and ActivityBeginTime <= '$time' 
                and ActivityEndTime >= '$time' ";
            //只有本店，部分商品
            $activity2 = TActivitySalesPromotion::find()
                ->where(" ActivityBeginDate <= '$data' and ActivityEndDate >='$data' and ActivityBeginTime <= '$time' 
                and ActivityEndTime >= '$time' and ActivityBranchIdList = $branchid ")
                ->andWhere($condition)
                ->andWhere("SpuIdList != '0' and SpuIdList != '1' ")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->all();
            $i = 0;
            if ($activity2) {
                foreach ($activity2 as $activity2_key => $activity2_value) {
                    $active[$i]['spu'] = explode(',', $activity2_value['SpuIdList']);
                    $active[$i]['userlevel'] = $activity2_value['UserLevel'];
                    $i++;
                }
            }
            //只有本店，全部商品
            $activity3 = TActivitySalesPromotion::find()
                ->where(" ActivityBeginDate <= '$data' and ActivityEndDate >='$data' and ActivityBeginTime <= '$time' 
                and ActivityEndTime >= '$time' and ActivityBranchIdList = $branchid")
                ->andWhere($condition)
                ->andWhere("SpuIdList = '0' or SpuIdList = '1' ")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->one();
            if ($activity3) {
                $spushop = TSpuShop::find()->select('SpuId')->where(['BranchId' => [$branchid, TBranchInfo::MSHOP]])->asArray()->all();
                $spuid = [];
                foreach ($spushop as $key => $value) {
                    $spuid[] = $value['SpuId'];
                }
                $active[$i]['spu'] = $spuid;
                $active[$i]['userlevel'] = $activity3['UserLevel'];
                $i++;
            }
            //多店 有本店，部分商品
            $activity4 = TActivitySalesPromotion::find()
                ->where(" ActivityBeginDate <= '$data' and ActivityEndDate >='$data' and ActivityBeginTime <= '$time' 
                and ActivityEndTime >= '$time' ")
                ->andWhere($condition)
                ->andWhere("ActivityBranchIdList != '0' and ActivityBranchIdList != '101'")
                ->andWhere("SpuIdList != '0' and SpuIdList != '1'")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->all();
            if ($activity4) {
                foreach ($activity4 as $activity4_key => $activity4_value) {
                    $activity4_res_branchid = in_array($branchid, explode(',', $activity4_value['ActivityBranchIdList']));
                    if ($activity4_res_branchid) {
                        $active[$i]['spu'] = explode(',', $activity4_value['SpuIdList']);
                        $active[$i]['userlevel'] = $activity4_value['UserLevel'];
                        $i++;
                    }
                }
            }
            //多店 有本店铺，全部商品
            $activity5 = TActivitySalesPromotion::find()
                ->where(" ActivityBeginDate <= '$data' and ActivityEndDate >='$data' and ActivityBeginTime <= '$time' 
                and ActivityEndTime >= '$time' ")
                ->andWhere($condition)
                ->andWhere("ActivityBranchIdList != '0' and ActivityBranchIdList != '101' ")
                ->andWhere("SpuIdList = '0' or SpuIdList = '1' ")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->all();
            if ($activity5) {
                foreach ($activity5 as $activity5_key => $activity5_value) {
                    $activity5_res_branchid = in_array($branchid, explode(',', $activity5_value['ActivityBranchIdList']));
                    if ($activity5_res_branchid) {
                        $spushop = TSpuShop::find()->select('SpuId')->where(['BranchId' => [$branchid, TBranchInfo::MSHOP]])->asArray()->all();
                        $spuid = [];
                        foreach ($spushop as $key => $value) {
                            $spuid[] = $value['SpuId'];
                        }
                        $active[$i]['spu'] = $spuid;
                        $active[$i]['userlevel'] = $activity5_value['UserLevel'];
                        $i++;
                    }
                }
            }
            //全部店铺 部分商品
            $activity6 = TActivitySalesPromotion::find()
                ->where(" ActivityBeginDate <= '$data' and ActivityEndDate >='$data' and ActivityBeginTime <= '$time' 
                and ActivityEndTime >= '$time' ")
                ->andWhere($condition)
                ->andWhere("ActivityBranchIdList = '0' or ActivityBranchIdList = '101' ")
                ->andWhere("SpuIdList != '0' and SpuIdList != '1' ")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->all();
            if ($activity6) {
                foreach ($activity6 as $activity6_key => $activity6_value) {
                    $active[$i]['spu'] = explode(',', $activity6_value['SpuIdList']);
                    $active[$i]['userlevel'] = $activity6_value['UserLevel'];
                    $i++;
                }
            }
            //全部店铺 全部商品
            $branchall = [0, TBranchInfo::MSHOP];
            $spuall = ['0', '1'];
            $activity7 = TActivitySalesPromotion::find()
                ->where(" ActivityBeginDate <= '$data' and ActivityEndDate >='$data' and ActivityBeginTime <= '$time' 
                and ActivityEndTime >= '$time' ")
                ->andWhere($condition)
                ->andWhere(['ActivityBranchIdList' => $branchall, 'SpuIdList' => $spuall])
                ->andWhere("EffectiveRange != 2")
                ->asArray()->one();
            if ($activity7) {
                $spushop = TSpuShop::find()->select('SpuId')->where(['BranchId' => [$branchid, TBranchInfo::MSHOP]])->asArray()->all();
                $spuid = [];
                foreach ($spushop as $key => $value) {
                    $spuid[] = $value['SpuId'];
                }
                $active[$i]['spu'] = $spuid;
                $active[$i]['userlevel'] = $activity7['UserLevel'];
            }

            //找完临时 再找周期促销
            $condition = ['ActivityStatus' => TActivitySalesPromotion::Activity_Status_Begin,
                'TimeType' => TActivitySalesPromotion::TimeType_Cycle, $todays[$today] => 1];
            //只有本店，部分商品
            $activity2_c = TActivitySalesPromotion::find()
                ->where(" ActivityBeginTime <= '$time' and ActivityEndTime >= '$time' and ActivityBranchIdList = $branchid ")
                ->andWhere($condition)
                ->andWhere("SpuIdList != '0' and SpuIdList != '1' ")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->all();
            if ($activity2_c) {
                foreach ($activity2_c as $activity2_c_key => $activity2_c_value) {
                    $active[$i]['spu'] = explode(',', $activity2_c_value['SpuIdList']);
                    $active[$i]['userlevel'] = $activity2_c_value['UserLevel'];
                    $i++;
                }
            }
            //只有本店，全部商品
            $activity3_c = TActivitySalesPromotion::find()
                ->where(" ActivityBeginTime <= '$time' and ActivityEndTime >= '$time' and ActivityBranchIdList = $branchid ")
                ->andWhere($condition)
                ->andWhere("SpuIdList = '0' or SpuIdList = '1' ")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->one();
            if ($activity3_c) {
                $spushop = TSpuShop::find()->select('SpuId')->where(['BranchId' => [$branchid, TBranchInfo::MSHOP]])->asArray()->all();
                $spuid = [];
                foreach ($spushop as $key => $value) {
                    $spuid[] = $value['SpuId'];
                }
                $active[$i]['spu'] = $spuid;
                $active[$i]['userlevel'] = $activity3_c['UserLevel'];
                $i++;
            }
            //多店 有本店，部分商品
            $activity4_c = TActivitySalesPromotion::find()
                ->where(" ActivityBeginTime <= '$time' and ActivityEndTime >= '$time' and ActivityBranchIdList = $branchid ")
                ->andWhere($condition)
                ->andWhere("ActivityBranchIdList != '0' and ActivityBranchIdList != '101'")
                ->andWhere("SpuIdList != '0' and SpuIdList != '1'")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->all();
            if ($activity4_c) {
                foreach ($activity4_c as $activity4_c_key => $activity4_c_value) {
                    $activity4_c_res_branchid = in_array($branchid, explode(',', $activity4_c_value['ActivityBranchIdList']));
                    if ($activity4_c_res_branchid) {
                        $active[$i]['spu'] = explode(',', $activity4_c_value['SpuIdList']);
                        $active[$i]['userlevel'] = $activity4_c_value['UserLevel'];
                        $i++;
                    }
                }
            }
            //多店 有本店铺，全部商品
            $activity5_c = TActivitySalesPromotion::find()
                ->where("  ActivityBeginTime <= '$time' and ActivityEndTime >= '$time' and ActivityBranchIdList = $branchid ")
                ->andWhere($condition)
                ->andWhere("ActivityBranchIdList != '0' and ActivityBranchIdList != '101' ")
                ->andWhere("SpuIdList = '0' or SpuIdList = '1' ")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->all();
            if ($activity5_c) {
                foreach ($activity5_c as $activity5_c_key => $activity5_c_value) {
                    $activity5_c_res_branchid = in_array($branchid, explode(',', $activity5_c_value['ActivityBranchIdList']));
                    if ($activity5_c_res_branchid) {
                        $spushop = TSpuShop::find()->select('SpuId')->where(['BranchId' => [$branchid, TBranchInfo::MSHOP]])->asArray()->all();
                        $spuid = [];
                        foreach ($spushop as $key => $value) {
                            $spuid[] = $value['SpuId'];
                        }
                        $active[$i]['spu'] = $spuid;
                        $active[$i]['userlevel'] = $activity5_c_value['UserLevel'];
                        $i++;
                    }
                }
            }
            //全部店铺 部分商品
            $activity6_c = TActivitySalesPromotion::find()
                ->where(" ActivityBeginTime <= '$time' and ActivityEndTime >= '$time' and ActivityBranchIdList = $branchid ")
                ->andWhere($condition)
                ->andWhere("ActivityBranchIdList = '0' or ActivityBranchIdList = '101' ")
                ->andWhere("SpuIdList != '0' and SpuIdList != '1' ")
                ->andWhere("EffectiveRange != 2")
                ->asArray()->all();
            if ($activity6_c) {
                foreach ($activity6_c as $activity6_c_key => $activity6_c_value) {
                    $active[$i]['spu'] = explode(',', $activity6_c_value['SpuIdList']);
                    $active[$i]['userlevel'] = $activity6_c_value['UserLevel'];
                    $i++;
                }
            }
            //全部店铺 全部商品
            $branchall = [0, TBranchInfo::MSHOP];
            $spuall = ['0', '1'];
            $activity7_c = TActivitySalesPromotion::find()
                ->where(" ActivityBeginTime <= '$time' and ActivityEndTime >= '$time' and ActivityBranchIdList = $branchid ")
                ->andWhere($condition)
                ->andWhere(['ActivityBranchIdList' => $branchall, 'SpuIdList' => $spuall])
                ->andWhere("EffectiveRange != 2")
                ->asArray()->one();
            if ($activity7_c) {
                $spushop = TSpuShop::find()->select('SpuId')->where(['BranchId' => [$branchid, TBranchInfo::MSHOP]])->asArray()->all();
                $spuid = [];
                foreach ($spushop as $key => $value) {
                    $spuid[] = $value['SpuId'];
                }
                $active[$i]['spu'] = $spuid;
                $active[$i]['userlevel'] = $activity7_c['UserLevel'];
            }
            if ($cache->exists('active' . $branchid)) {
                $cache->set('active' . $branchid, $active, 3600);
            } else {
                $cache->add('active' . $branchid, $active, 3600);
            }
        }
        if ($cache->get('active' . $branchid)) {
            $active = $cache->get('active' . $branchid);
            if ($active) {
                foreach ($active as $k => $v) {
                    if ($userlevel >= $v['userlevel']) {
                        if (in_array($this->SpuId, $v['spu'])) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    //转换为数组时需要处理的字段
    public function fields()
    {
        $extraFields = [
            'formatPrice' => function ($model) {
                return $model->formatPrice;
            },
            'formatMemberPrice' => function ($model) {
                return $model->formatMemberPrice;
            },
            'coverImg' => function ($model) {
                return $model->coverImg;
            },
            'hasSpecialPrice' => function ($model) {
                return $model->hasSpecialPrice();
            }
        ];
        return array_merge(parent::fields(), $extraFields);
    }

    //用于显示的商品详情
    public function getContent()
    {
        if ($this->SpuDetailType == TSpu::DETAIL_TYPE_IMG && $this->SpuDetail) {
            $json = json_decode($this->SpuDetail);
            $html = [];
            foreach ($json as $img) {
                $html[] = sprintf('<img src="%s"/>', $img);
            }
            return join('', $html);
        } else {
            return $this->SpuDetailType == TSpu::DETAIL_TYPE_TEXT ? $this->SpuDetail : $this->SpuDetailHtml;
        }
    }

    //是否含有特价的sku
    public function hasSpecialPrice()
    {
        return $this->SpuPriceType == TSku::TYPE_SPECIAL;
    }

    private $_skuList;

    //获取某个spu对应的sku列表，用于前台选择，只选择当前门让的skuList
    public function skuList()
    {
        if ($this->_skuList) {
            return $this->_skuList;
        }
        $vectorList = json_decode($this->SpuVector, true);
        if (!$vectorList) {
            return [];
        }
        $skuIdList = array_column($vectorList, 'sku');
        $fields = ['SkuId', 'SkuPrice', 'SkuNum', 'SkuVector', 'SkuPriceType', 'SkuMemberPrice'];
        $this->_skuList = TSku::find()->where(['SkuId' => $skuIdList, 'BranchId' => $this->BranchId])
            ->groupBy('SkuId')->select($fields)->all();
        return $this->_skuList;
    }

    public function getSkuVector()
    {
        $vectorList = [];
        foreach ($this->skuList() as $sku) {
            $json = $sku->skuVectorJson;
            foreach ($json as $row) {
                $vectorList[$row['name']][] = $row['value'];
            }
        }
        foreach ($vectorList as &$vector) {
            $vector = array_unique($vector);
        }
        //var_dump($vectorList);
        return $vectorList;
    }

    /*
     * 商品详情页获取规格
     * */
    public function getSkuSpec()
    {
        $vectorList = [];
        foreach ($this->skuList() as $k => $sku) {
            $json = $sku->skuVectorJson;
            $vectorList[$k]['SkuPrice'] = $sku['SkuPrice'];
            $vectorList[$k]['SkuMemberPrice'] = $sku['SkuMemberPrice'];
            $vectorList[$k]['SkuPriceType'] = $sku['SkuPriceType'];
            $vectorList[$k]['PriceRule'] = TConfig::getPriceRule()['ConfigValue'];
            $vectorList[$k]['SkuId'] = $sku['SkuId'];
            $vectorList[$k]['SkuNum'] = $sku['SkuNum'];
            $vectorList[$k]['SkuVector'] = $json;
            /*foreach($json as $row){
                $vectorList[$k]['SkuVector'] = $row;
            }*/
        }
        /*foreach($vectorList as &$vector){
            $vector = array_unique($vector);
        }*/
        return $vectorList;
    }


    //给js使用的商品sku列表
    public function getSkuForJs()
    {
        $res = [];
        foreach ($this->skuList() as $sku) {
            $arr = $sku->toArray();
            $arr['SkuVector'] = $sku->skuVectorJson;
            $arr['SkuPrice'] = $sku->SkuPrice ?: $this->ShowPrice;
            $arr['SkuMemberPrice'] = $sku->SkuPrice ?: $this->ShowMemberPrice;
            $arr['isSpecialPrice'] = $sku->isSpecialPrice();
            unset($arr['SkuPriceType']);
            $res[] = $arr;
        }
        return $res;
    }


    //是否可以自提
    public function canSelfTake()
    {
        return $this->TransactionMeans == self::TRANSACTION_DEFAULT || $this->TransactionMeans == self::TRANSACTION_SELF_TAKE;
    }

    //是否上架
    public function isOnline()
    {
        return $this->ShopStatus == self::STATUS_ONLINE;
    }

    public function getSpu()
    {
        return $this->hasOne(TSpu::className(), ['SpuId' => 'SpuId']);
    }

    public function getCategoryAttribute()
    {
        return $this->hasMany(TCategoryAttribute::className(), ['CategoryId' => 'CategoryId']);
    }

    /**
     * 按分店查询，有分店的商品出分店的，没有出微商城的，商品不能重复
     * 这里的逻辑是先将所有商品按branchId倒排序，由于微商城的branchId最小，所以排在最后
     * 为了让商品不重复(SpuId)，只能先将SpuShopId和SpuId全部查出，再进行过滤，获取所有商品的id列表
     * 分页时，直接根据id列表和offset取出对应的SpuShopId列表，再去表里做in查询
     *
     * @param  TBranchInfo $branch 分店对象
     * @param  integer $limit 分页的每页记录数
     * @param  integer $offset 分页的偏移量
     * @param  \Closure|null $filter 过滤器，可以通过closure给query对象赋值各种query条件
     * @return array TSpuShop对象列表
     */
    public static function findByBranch($branchId, $limit = null, $offset = 0, \Closure $filter = null)
    {
        $query = TSpuShop::find()->select('SpuShopId, SpuId, BranchId');
        $branch = TBranchInfo::findOne($branchId);
        if ($branch->BranchType == TBranchInfo::TYPE_INDEPENDENT) {
            $query->andWhere(['BranchId' => [$branchId], 'ShopStatus' => 1]);
        } else {
            $query->andWhere(['BranchId' => [$branchId, TBranchInfo::MSHOP], 'ShopStatus' => 1]);
        }
        if ($filter) {
            $filter($query);
        }
        $shopIdList = $query->asArray()->all();
        $shopIdMap = [];
        foreach ($shopIdList as $row) {
            $spuId = $row['SpuId'];
            if (!isset($shopIdMap[$spuId])) {
                $shopIdMap[$spuId] = $row['SpuShopId'];
            } else if ($row['BranchId'] != TBranchInfo::MSHOP) {
                $shopIdMap[$spuId] = $row['SpuShopId'];
            }
        }
        $idList = array_values($shopIdMap);
        $query = TSpuShop::find()->select('SpuShopId,SpuId,ShowPrice,ImgUrl,SpuName,SpuPriceType,BranchId,ShowMemberPrice');
        $spuList = $query->where(['SpuShopId' => $idList])->orderBy('SpuWeight desc')
            ->offset($offset)->limit($limit)->all();
        $spuShopAdapter = new SpuShopAdapter;
        $spuList = $spuShopAdapter->updateSpuList($spuList, $branchId);
        return $spuList;
    }

    /**
     * ShowPrice为$branchid店铺的SpuId为$spuId的所有Sku的最低的SkuPrice
     */
    public static function getSpuShopShowPrice($branchId, $spuId)
    {
        $spuId = strval($spuId);
        $skuPrice = TSku::find()->select('SkuPrice')
            ->where(['SpuId' => $spuId, 'BranchId' => $branchId])
            ->min('SkuPrice');
        if (empty($skuPrice)) {
            $skuPrice =  TSku::find()->select('SkuPrice')
                ->where(['SpuId' => $spuId, 'BranchId' => '101'])
                ->min('SkuPrice');
        }
        return $skuPrice;
    }

    public static function UpGoods($spuinfo, $workerid, $branchid)
    {
        $spu_shop = new TSpuShop();
        $spu_shop->SpuId = $spuinfo['SpuId'];
        $spu_shop->BranchId = $branchid;
        $spu_shop->SpuName = $spuinfo['SpuName'];
        $spu_shop->OnDate = date('Y-m-d H:i:s', time());

        $SpuShopShowPrice = static::getSpuShopShowPrice($branchid, $spuinfo['SpuId']);

        $spu_shop->ShowPrice = ($SpuShopShowPrice > 0) ? $SpuShopShowPrice : $spuinfo['SpuPrice'];
        $spu_shop->CategoryId = $spuinfo['CategoryId'];
        $spu_shop->CategoryIdSub = $spuinfo['CategoryIdSub'];
        $spu_shop->CategoryIdTre = $spuinfo['CategoryIdTre'];
        $spu_shop->WorkerId = $workerid;

        $spu_shop->save();
        return $spu_shop->primaryKey;
    }

    //上架商品的详细信息
    public static function getSpuShop($spuid, $branchid)
    {
        //当你看到这段代码的时候，你会被这个逻辑整奔溃
        $spu_shop_branch = TSpuShop::find()
            ->where(['SpuId' => $spuid, 'BranchId' => $branchid, 'ShopStatus' => 1])
            ->asArray()->one();
        $spu_shop_101 = TSpuShop::find()
            ->where(['SpuId' => $spuid, 'BranchId' => 101, 'ShopStatus' => 1])
            ->asArray()->one();
        if ($spu_shop_branch) {
            //取图本店有就用本店，本店没有用101
            if (!$spu_shop_branch['ImgUrl']) {
                if ($spu_shop_101) {
                    $spu_shop_branch['ImgUrl'] = $spu_shop_101['ImgUrl'];
                }
            }
            $spu_shop = $spu_shop_branch;
        } else {
            $spu_shop = $spu_shop_101;
        }
        if ($spu_shop) {
            $category = TCategory::getCategoryName($spu_shop['CategoryId'],
                $spu_shop['CategoryIdSub'], $spu_shop['CategoryIdTre']);
            $spu_shop['category'] = $category ? $category : [];
            //商品tag标签
            $spu = TSpu::findOne($spu_shop['SpuId']);
            $categoryattribute = json_decode($spu['SpuAttribute'], true);
            $tag = [];
            if ($categoryattribute) {
                foreach ($categoryattribute as $key => $v) {
                    if (isset($v['name'])) {
                        $tag[$key]['name'] = $v['name'];
                    }
                    if (isset($v['tags'])) {
                        $tag[$key]['tags'] = $v['tags'];
                    }
                }
            }
            $spu_shop['tag'] = $tag;
            $data['ImgUrl'] = json_decode($spu_shop['ImgUrl'], true);
            if ($data['ImgUrl']) {
                $spu_shop['ImgUrl'] = array_filter($data['ImgUrl']);
            }
            $spu_shop['ExpressPrice'] = $spu_shop['ExpressPrice'] / 100;
            if ($spu_shop['SpuDetailType'] == 0) {
                $spu_shop['SpuDetail'] = json_decode($spu_shop['SpuDetail'], true);
            }
            $workerinfo = TWorkerInfo::findOne($spu_shop['WorkerId']);
            $spu_shop['workername'] = $workerinfo ? $workerinfo['WorkerName'] : '';
            $spu_shop['SpuPrice'] = $spu_shop['ShowPrice'];
        }
        return $spu_shop;
    }

    //校验数据
    public static function checkForm($params)
    {
        if (!isset($params['imgurl'])) {
            return '图片不能为空';
        }

        if (!isset($params['ExpressPrice']) || !is_numeric($params['ExpressPrice'])) {
            return '请填写正确的运费';
        }
    }

    //添加商品详情
    public static function addGoodDetail($params, $branchid, $workerid)
    {
        //超级管理员上架的时候需要操作微商城店铺
        if ($branchid == 0) {
            $branchid = 101;
        }
        $spu = TSpu::findOne($params['spushopid']);
        $spu_shop = TSpuShop::find()
            ->where(['SpuId' => $params['spushopid'], 'BranchId' => $branchid])
            ->one();
        $spu_shop->ImgUrl = json_encode($params['imgurl'], JSON_UNESCAPED_UNICODE);
        $spu_shop->SpuDetailType = $params['SpuDetailType'];
        if ($params['SpuDetailType'] == 0) {
            $spu_shop->SpuDetail = json_encode($params['spuimg'], JSON_UNESCAPED_UNICODE);
        } elseif ($params['SpuDetailType'] == 1) {
            $spu_shop->SpuDetail = $params['SpuDetail'];
        } elseif ($params['SpuDetailType'] == 2) {
            $spu_shop->SpuDetailHtml = $params['SpuDetail'];
        }
        $spu_shop->ExpressPrice = $params['ExpressPrice'] * 100;
        $spu_shop->SpuWeight = $params['SpuWeight'];
        $spu_shop->WorkerId = $workerid;
        $spu_shop->ShopStatus = 1;
        $spu_shop->OnDate = date('Y-m-d H:i:s', time());
        if (isset($params['spuprice'])) {
            $spu_shop->ShowPrice = $params['spuprice'] * 100;
        }
        if (isset($params['packdetail'])) {
            $spu_shop->PackDetail = $params['packdetail'] ? $params['packdetail'] : '';
            $spu_shop->SpuType = 3;
        }
        $spu_shop->Period = $spu->Period;
        if ($spu_shop->save()) {
            return $spu_shop->primaryKey;
        } else {
            return 2;
        }
    }

    //添加商品的库存列表
    public static function getSkuList($spuid, $branchid)
    {
        $skulist = TSku::getSkuList($spuid, $branchid);
        $sku_list = [];
        foreach ($skulist as $key => $v) {
            $sku_list[$key]['vector'] = json_decode($v['SkuVector']);
            $sku_list[$key]['price'] = $v['SkuPrice'];
            $sku_list[$key]['type'] = $v['SkuPriceType'];
            $sku_list[$key]['sku'] = $v['SkuId'];
            $sku_list[$key]['count'] = $v['SkuNum'];
            $sku_list[$key]['branchid'] = $v['BranchId'];
            $branch = TBranchInfo::getBranch($v['BranchId']);
            $sku_list[$key]['branchname'] = $branch['BranchName'];
        }
        return $sku_list;
    }

    //获取微商城的上架商品list
    public static function getSpuShopList($branchid, $page, $count, $arr)
    {
        if ($branchid == 101) {
            $data = TSpuShop::find()->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])->orderBy('OnDate desc');
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $count]);
            $spushoplist = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all();
            foreach ($spushoplist as $key => $spu) {
                //展示价格
                $spushoplist[$key]['downable'] = true;
                $worker = TWorkerInfo::findOne($spu['WorkerId']);
                $spushoplist[$key]['WorkerName'] = $worker['WorkerName'];
                //上架库存数量
                $skulist = json_decode($spu['SpuVector'], true);
                $num = 0;
                foreach ($skulist as $k => $v) {
                    $sku = TSku::find()
                        ->where(['BranchId' => $branchid, 'SkuId' => $v['sku']])
                        ->asArray()->one();
                    $num += $sku['SkuNum'];
                }
                $spushoplist[$key]['count'] = $num;
                //商品分类
                $category = TCategory::getCategory($spu['CategoryId']);
                $spushoplist[$key]['CategoryIdName'] = $category ? $category['CategoryName'] : '';
                $category2 = TCategory::getCategory($spu['CategoryIdSub']);
                $spushoplist[$key]['CategoryIdSubName'] = $category2 ? $category2['CategoryName'] : '';
                $category3 = TCategory::getCategory($spu['CategoryIdTre']);
                $spushoplist[$key]['CategoryIdTreName'] = $category3 ? $category3['CategoryName'] : '';

                $pagelist = TPageList::find()->where(['SpuId' => $spu['SpuId'], 'BranchId' => $spu['BranchId']])->asArray()->all();
                $page_name = [];
                foreach ($pagelist as $k => $item) {
                    $pagehome = TPageHome::find()->where(['PageId' => $item['PageId']])->asArray()->one();
                    if ($pagehome) {
                        $page_name[] = $pagehome['PageType'];
                    }
                    if ($item['PageId'] == 0) {
                        $page_name[] = '0';
                    }
                }
                $page_name = array_unique($page_name);
                $name = '';
                if (in_array('0', $page_name, true)) {
                    $name .= '首页';
                }
                if (in_array('1', $page_name, true)) {
                    $name .= ' 推广';
                }
                if (in_array('2', $page_name, true)) {
                    $name .= ' 运营';
                }
                $spushoplist[$key]['name'] = $name;
            }
            $pageall = ceil($data->count() / $count);
            $data = ['pages' => $pageall, 'page' => $page, 'list' => $spushoplist];
        } else {
            //$branchtype = $arr['branchtype'];
            if($branchid){
                $branch_info = TBranchInfo::find()->where(['BranchId'=>$branchid])->one();
                $branchtype = $branch_info->BranchType;
            }else{
                $branchtype = $arr['branchtype'];
            }
            $spushoplist = [];
            //获取非101的上架商品
            $data2 = TSpuShop::find()
                ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                ->orderBy('OnDate desc')
                ->asArray()->all();
            if (!is_array($branchid)) {
                $branchid = explode(',', $branchid);
            }
            foreach ($data2 as $key => $spu) {
                if (in_array($spu['BranchId'], $branchid)) {
                    $data2[$key]['downable'] = true;
                } else {
                    $data2[$key]['downable'] = false;
                }
                $worker = TWorkerInfo::findOne($spu['WorkerId']);
                $data2[$key]['WorkerName'] = $worker['WorkerName'];
                //上架库存数量
                $skulist = json_decode($spu['SpuVector'], true);
                $num = 0;
                if ($skulist) {
                    foreach ($skulist as $k => $v) {
                        $sku = TSku::find()
                            ->where(['BranchId' => $spu['BranchId'], 'SkuId' => $v['sku']])
                            ->asArray()->one();
                        $num += $sku['SkuNum'];
                    }
                }
                $data2[$key]['count'] = $num;
                //商品分类
                $category = TCategory::getCategory($spu['CategoryId']);
                $data2[$key]['CategoryIdName'] = $category ? $category['CategoryName'] : '';
                $category2 = TCategory::getCategory($spu['CategoryIdSub']);
                $data2[$key]['CategoryIdSubName'] = $category2 ? $category2['CategoryName'] : '';
                $category3 = TCategory::getCategory($spu['CategoryIdTre']);
                $data2[$key]['CategoryIdTreName'] = $category3 ? $category3['CategoryName'] : '';
                $pagelist = TPageList::find()->where(['SpuId' => $spu['SpuId'], 'BranchId' => $spu['BranchId']])->asArray()->all();
                $page_name = [];
                foreach ($pagelist as $k => $item) {
                    $pagehome = TPageHome::find()->where(['PageId' => $item['PageId']])->asArray()->one();
                    if ($pagehome) {
                        $page_name[] = $pagehome['PageType'];
                    }
                    if ($item['PageId'] == 0) {
                        $page_name[] = '0';
                    }
                }
                $page_name = array_unique($page_name);
                $name = '';
                if (in_array('0', $page_name, true)) {
                    $name .= '首页';
                }
                if (in_array('1', $page_name, true)) {
                    $name .= ' 推广';
                }
                if (in_array('2', $page_name, true)) {
                    $name .= ' 运营';
                }
                $data2[$key]['name'] = $name;
            }
            if ($branchtype != 3 && $branchtype != 2) {
                //101上架商品
                $spushoplist = TSpuShop::find()
                    ->where(['BranchId' => 101, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                    ->orderBy('OnDate desc')
                    ->asArray()->all();
                foreach ($spushoplist as $key => $spu) {
                    if ($spu['BranchId'] == $branchid) {
                        $spushoplist[$key]['downable'] = true;
                    } else {
                        $spushoplist[$key]['downable'] = false;
                    }
                    $worker = TWorkerInfo::findOne($spu['WorkerId']);
                    $spushoplist[$key]['WorkerName'] = $worker['WorkerName'];
                    //上架库存数量
                    $skulist = json_decode($spu['SpuVector'], true);
                    $num = 0;
                    foreach ($skulist as $k => $v) {
                        $sku = TSku::find()
                            ->where(['BranchId' => 101, 'SkuId' => $v['sku']])
                            ->asArray()->one();
                        $num += $sku['SkuNum'];
                    }
                    $spushoplist[$key]['count'] = $num;
                    //商品分类
                    $category = TCategory::getCategory($spu['CategoryId']);
                    $spushoplist[$key]['CategoryIdName'] = $category ? $category['CategoryName'] : '';
                    $category2 = TCategory::getCategory($spu['CategoryIdSub']);
                    $spushoplist[$key]['CategoryIdSubName'] = $category2 ? $category2['CategoryName'] : '';
                    $category3 = TCategory::getCategory($spu['CategoryIdTre']);
                    $spushoplist[$key]['CategoryIdTreName'] = $category3 ? $category3['CategoryName'] : '';
                    $pagelist = TPageList::find()->where(['SpuId' => $spu['SpuId'], 'BranchId' => $spu['BranchId']])->asArray()->all();
                    $page_name = [];
                    foreach ($pagelist as $k => $item) {
                        $pagehome = TPageHome::find()->where(['PageId' => $item['PageId']])->asArray()->one();
                        if ($pagehome) {
                            $page_name[] = $pagehome['PageType'];
                        }
                        if ($item['PageId'] == 0) {
                            $page_name[] = '0';
                        }
                    }
                    $page_name = array_unique($page_name);
                    $name = '';
                    if (in_array('0', $page_name, true)) {
                        $name .= '首页';
                    }
                    if (in_array('1', $page_name, true)) {
                        $name .= ' 推广';
                    }
                    if (in_array('2', $page_name, true)) {
                        $name .= ' 运营';
                    }
                    $spushoplist[$key]['name'] = $name;
                }
                //合并去重
                foreach ($spushoplist as $key => $value) {
                    foreach ($data2 as $k => $v) {
                        if ($v['SpuId'] == $value['SpuId']) {
                            unset($spushoplist[$key]);
                        }
                    }
                }
            }

            $spushoplist = array_merge($data2, $spushoplist);
            $pageData = [];
            if ($spushoplist) {
                //总页数
                $pagesall = ceil(count($spushoplist) / $count);
                if ($pagesall < 1) {
                    $pagesall = 0;
                }
                if ($page <= 1) {
                    $page = 1;
                }
                //当前分页
                if ($page >= $pagesall) {
                    $page = $pagesall;
                    $startIndex = ($page - 1) * $count;
                    $endIndex = count($spushoplist);
                } else {
                    $startIndex = ($page - 1) * $count;
                    $endIndex = $startIndex + $count;
                }
                //每页的数据

                for ($n = $startIndex; $n < $endIndex; $n++) {
                    if ($n < count($spushoplist)) {
                        $pageData[] = $spushoplist[$n];
                    }
                }
            } else {
                $pagesall = 0;
                $page = 0;
            }
            $data = ['pages' => $pagesall, 'page' => $page, 'list' => $pageData];
        }
        return $data;
    }

    /**
     * 通过关键字搜索商品
     * @param unknown $search 搜索内容
     * @param unknown $count 每页多少条
     * @param unknown $page 当前页数
     */
    public static function getSpuForSearch($search, $count, $page, $branchid)
    {
        if (is_numeric($search)) {
            $data = TSpuShop::find()
                ->where("SpuId like :SpuId or SpuVector like :SpuVector")
                ->addParams([':SpuId' => "%$search%"])
                ->addParams([':SpuVector' => "%$search%"])
                ->orderBy(' SpuId asc ');
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $count]);
            $spu_list = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all();
            $spulist = [];
            foreach ($spu_list as $key => $spu) {
                if ($spu['BranchId'] == $branchid) {
                    $spulist[$key]['operable'] = true;
                } else {
                    $spulist[$key]['operable'] = false;
                }
                $spulist[$key]['spuid'] = $spu['SpuId'];
                $spulist[$key]['name'] = $spu['SpuName'];
                $spulist[$key]['timestamp'] = strtotime($spu['OnDate']);
                //获取分类的名称
                $categoryname = TCategory::getCategoryName($spu['CategoryId'], $spu['CategoryIdSub'], $spu['CategoryIdTre']);
                $spulist[$key]['category'] = $categoryname;
                //商品维度
                if ($spu['SpuVector'] != '') {
                    $vector = TSpu::getVector($spu['SpuVector']);
                    $spulist[$key]['tag'] = $vector;
                }
            }
        } else {
            //商品名称搜索
            $data = TSpuShop::find()
                ->where("t_spu.SpuName like :SpuName or SpuId like :SpuId")
                ->addParams([':SpuName' => "%$search%"])
                ->addParams([':SpuId' => "%$search%"])
                ->orderBy(' SpuId asc ');
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $count]);
            $spu_list = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all();
            $spulist = [];
            foreach ($spu_list as $key => $spu) {
                if ($spu['BranchId'] == $branchid) {
                    $spulist[$key]['operable'] = true;
                } else {
                    $spulist[$key]['operable'] = false;
                }
                $spulist[$key]['spuid'] = $spu['SpuId'];
                $spulist[$key]['name'] = $spu['SpuName'];
                $spulist[$key]['timestamp'] = strtotime($spu['OnDate']);
                //获取分类的名称
                $categoryname = TCategory::getCategoryName($spu['CategoryId'], $spu['CategoryIdSub'], $spu['CategoryIdTre']);
                $spulist[$key]['category'] = $categoryname;
                //商品维度
                if ($spu['SpuVector'] != '') {
                    $vector = TSpu::getVector($spu['SpuVector']);
                    $spulist[$key]['tag'] = $vector;
                }
            }
        }
        $pageall = ceil($data->count() / $count);
        $data = ['pages' => $pageall, 'page' => $page, 'list' => $spulist];
        return $data;
    }

    //获取上架的库存
    public static function getUpSku($branchid)
    {
        $spulist = TSpuShop::find()
            ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => 1])
            ->asArray()->all();
        $skulist = [];
        foreach ($spulist as $key => $item) {
            if (json_decode($item['SpuVector'], true)) {
                $skulist = array_merge(json_decode($item['SpuVector'], true), $skulist);
            }
        }
	$retSkuList = [];
        foreach ($skulist as $k => $v) {
            $sku = TSku::find()->where(['SkuId' => $v['sku'], 'BranchId' => $branchid])
                ->asArray()->one();
	    if(is_null($sku)){
		continue;
	    }
            $spu = TSpu::findOne($sku['SpuId']);
            $skulist[$k]['name'] = $spu['SpuName'];
            $skulist[$k]['count'] = $sku['SkuNum'];
            $skulist[$k]['price'] = $sku['SkuPrice'];
            //当未设置会员价或者会员价为负数时，设置会员价字段为空
            $skulist[$k]['memberPrice'] = (!isset($sku['SkuMemberPrice']) || $sku['SkuMemberPrice'] < 0) ? '' : $sku['SkuMemberPrice'];
	    $skulist[$k]['Vector'] = $sku['SkuVector'];
            $retSkuList[] = $skulist[$k];
        }
        return $retSkuList;
    }

    //获取搜索上架sku
    public static function searchUpSku($branchid, $search)
    {
        $spulist = TSpuShop::find()
            ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
            ->andWhere('SpuId like :SpuId or SpuVector like :SpuVector or SpuName like :SpuName')
            ->addParams([':SpuId' => "%$search%"])
            ->addParams([':SpuVector' => "%$search%"])
            ->addParams([':SpuName' => "%$search%"])
            ->asArray()->all();
        $skulist = [];
        foreach ($spulist as $item) {
            if (json_decode($item['SpuVector'], true)) {
                $skulist = array_merge(json_decode($item['SpuVector'], true), $skulist);
            }
        }
        foreach ($skulist as $k => $v) {
            $sku = TSku::find()->where(['SkuId' => $v['sku'], 'BranchId' => $branchid])
                ->asArray()->one();
            $spu = TSpu::findOne($sku['SpuId']);
            $skulist[$k]['name'] = $spu['SpuName'];
            $skulist[$k]['count'] = $sku['SkuNum'];
            $skulist[$k]['price'] = $sku['SkuPrice'];
            $skulist[$k]['memberPrice'] = $sku['SkuMemberPrice'];
        }
        return $skulist;
    }


    /**获取搜索上架库存
     * @param $keyword //关键字
     * @param $branchid //店铺ID
     * @param $arr //基类数组
     * @return array
     */
    public static function getSearchUpSpu($keyword, $branchid, $arr)
    {
        $spulist = [];
        if (!$branchid) {
            $branchlist = $arr['branchlist'];
            $branchidlist = [];
            foreach ($branchlist as $key => $value) {
                $branchidlist[] = $value['BranchId'];
            }
            $branchid = $branchidlist;
        }
        $branchtype = $arr['branchtype'];
        #####################charis添加按照分类搜索######################
        $cateName = TCategory::getCategoryId($keyword, $branchid);
        if (!empty($cateName)) {
            $categoryId = $cateName['CategoryId'];
        } else {
            $categoryId = '    ';
        }
        #########################end#########################################
        switch ($branchtype) {
            case 0:
                if ($branchid == TBranchInfo::MSHOP) {
                    $spulist = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                } else {
                    $data2 = TSpuShop::find()
                        ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    $data101 = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    //过滤掉101店铺的上架商品
                    foreach ($data101 as $key => $value) {
                        foreach ($data2 as $k => $v) {
                            if ($v['SpuId'] == $value['SpuId']) {
                                unset($data101[$key]);
                            }
                        }
                    }
                    if (count($data101)) {
                        $spulist = array_merge($data2, $data101);
                    } else {
                        $spulist = $data2;
                    }
                }
                break;
            case 1:
                if ($branchid == TBranchInfo::MSHOP) {
                    $spulist = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                } else {
                    $data2 = TSpuShop::find()
                        ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    $data101 = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    //过滤掉101店铺的上架商品
                    foreach ($data101 as $key => $value) {
                        foreach ($data2 as $k => $v) {
                            if ($v['SpuId'] == $value['SpuId']) {
                                unset($data101[$key]);
                            }
                        }
                    }
                    if (count($data101)) {
                        $spulist = array_merge($data2, $data101);
                    } else {
                        $spulist = $data2;
                    }
                }
                break;
            case 2:
                if ($branchid == TBranchInfo::MSHOP) {
                    $spulist = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                } else {
                    $data2 = TSpuShop::find()
                        ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    $data101 = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->addParams([':CategoryId' => "%$categoryId%"])
                        ->addParams([':CategoryIdSub' => "%$categoryId%"])
                        ->addParams([':CategoryIdTre' => "%$categoryId%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    //过滤掉101店铺的上架商品
                    foreach ($data101 as $key => $value) {
                        foreach ($data2 as $k => $v) {
                            if ($v['SpuId'] == $value['SpuId']) {
                                unset($data101[$key]);
                            }
                        }
                    }
                    if (count($data101)) {
                        $spulist = array_merge($data2, $data101);
                    } else {
                        $spulist = $data2;
                    }
                }
                break;
            case 3:
                $spulist = TSpuShop::find()
                    ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                    ->andWhere("SpuId like :SpuId
                        or SpuName like :SpuName
                        or CategoryID like :CategoryId
                        or CategoryIdSub like :CategoryIdSub
                        or CategoryIdTre like :CategoryIdTre")
                    ->addParams([':SpuId' => "%$keyword%"])
                    ->addParams([':SpuName' => "%$keyword%"])
                    ->addParams([':CategoryId' => "%$categoryId%"])
                    ->addParams([':CategoryIdSub' => "%$categoryId%"])
                    ->addParams([':CategoryIdTre' => "%$categoryId%"])
                    ->orderBy(' OnDate desc ')
                    ->asArray()->all();
                break;
            case 10:
                break;
            default :
                break;
        }

        foreach ($spulist as $key => $spu) {
            $worker = TWorkerInfo::findOne($spu['WorkerId']);
            $spulist[$key]['WorkerName'] = $worker['WorkerName'];
            if ($spu['BranchId'] == $branchid) {
                $spulist[$key]['operable'] = true;
            } else {
                $spulist[$key]['operable'] = false;
            }
            //库存数量
            $skulist = TSku::find()
                ->where(['BranchId' => $spu['BranchId'], 'SpuId' => $spu['SpuId']])
                ->asArray()->all();
            $num = 0;
            foreach ($skulist as $k => $v) {
                $num += $v['SkuNum'];
            }
            $spulist[$key]['count'] = $num;
            //商品分类
            $category = TCategory::getCategory($spu['CategoryId']);
            $spulist[$key]['CategoryIdName'] = $category ? $category['CategoryName'] : '';
            $category2 = TCategory::getCategory($spu['CategoryIdSub']);
            $spulist[$key]['CategoryIdSubName'] = $category2 ? $category2['CategoryName'] : '';
            $category3 = TCategory::getCategory($spu['CategoryIdTre']);
            $spulist[$key]['CategoryIdTreName'] = $category3 ? $category3['CategoryName'] : '';
            //首页说明
            $pagelist = TPageList::find()->where(['SpuId' => $spu['SpuId'], 'BranchId' => $spu['BranchId']])->asArray()->all();
            $page_name = [];
            foreach ($pagelist as $k => $item) {
                $pagehome = TPageHome::find()->where(['PageId' => $item['PageId']])->asArray()->one();
                if ($pagehome) {
                    $page_name[] = $pagehome['PageType'];
                }
                if ($item['PageId'] == 0) {
                    $page_name[] = '0';
                }
            }
            $page_name = array_unique($page_name);
            $name = '';
            if (in_array('0', $page_name, true)) {
                $name .= '首页';
            }
            if (in_array('1', $page_name, true)) {
                $name .= ' 推广';
            }
            if (in_array('2', $page_name, true)) {
                $name .= ' 运营';
            }
            $spulist[$key]['name'] = $name;
        }
        return $spulist;
    }

    //获取微商城的上架商品list
    public static function getSpuShopListForScore($branchid, $page, $count, $arr, \Closure $closure = null)
    {
        if (in_array(101, $branchid)) {
            $data = TSpuShop::find()->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])->orderBy('OnDate desc');
//            $data->leftJoin()
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $count]);
            if ($closure) $closure($data);
            $spushoplist = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all();
            $pageall = ceil($data->count() / $count);
            $data = ['pages' => $pageall, 'page' => $page, 'list' => $spushoplist];
        } else {
            $branchtype = $arr['branchtype'];
            $spushoplist = [];
            //获取非101的上架商品
            if (!is_array($branchid)) {
                $branchid = explode(',', $branchid);
            }
            $data2 = TSpuShop::find()
                ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                ->orderBy('OnDate desc');
            if ($closure) $closure($data2);
            $data2 = $data2->asArray()->all();
            if ($branchtype != 3) {
                //101上架商品
                $spushoplist = TSpuShop::find()
                    ->where(['BranchId' => 101, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                    ->orderBy('OnDate desc');
                if ($closure) $closure($spushoplist);
                $spushoplist = $spushoplist->asArray()->all();
                //合并去重
                foreach ($spushoplist as $key => $value) {
                    foreach ($data2 as $k => $v) {
                        if ($v['SpuId'] == $value['SpuId']) {
                            unset($spushoplist[$key]);
                        }
                    }
                }
            }

            $spushoplist = array_merge($data2, $spushoplist);
            $pageData = [];
            if ($spushoplist) {
                //总页数
                $pagesall = ceil(count($spushoplist) / $count);
                if ($pagesall < 1) {
                    $pagesall = 0;
                }
                if ($page <= 1) {
                    $page = 1;
                }
                //当前分页
                if ($page >= $pagesall) {
                    $page = $pagesall;
                    $startIndex = ($page - 1) * $count;
                    $endIndex = count($spushoplist);
                } else {
                    $startIndex = ($page - 1) * $count;
                    $endIndex = $startIndex + $count;
                }
                //每页的数据

                for ($n = $startIndex; $n < $endIndex; $n++) {
                    if ($n < count($spushoplist)) {
                        $pageData[] = $spushoplist[$n];
                    }
                }
            } else {
                $pagesall = 0;
                $page = 0;
            }
            $data = ['pages' => $pagesall, 'page' => $page, 'list' => $pageData];
        }
        return $data;
    }

    /**获取搜索上架库存
     * @param $keyword //关键字
     * @param $branchid //店铺ID
     * @param $arr //基类数组
     * @return array
     */
    public static function getSearchUpSpuForScore($keyword, $branchid, $arr)
    {
        $spulist = [];
        if (!$branchid) {
            $branchlist = $arr['branchlist'];
            $branchidlist = [];
            foreach ($branchlist as $key => $value) {
                $branchidlist[] = $value['BranchId'];
            }
            $branchid = $branchidlist;
        }
        $branchtype = $arr['branchtype'];
        switch ($branchtype) {
            case 0:
                if ($branchid == TBranchInfo::MSHOP) {
                    $spulist = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                } else {
                    $data2 = TSpuShop::find()
                        ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    $data101 = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    //过滤掉101店铺的上架商品
                    foreach ($data101 as $key => $value) {
                        foreach ($data2 as $k => $v) {
                            if ($v['SpuId'] == $value['SpuId']) {
                                unset($data101[$key]);
                            }
                        }
                    }
                    if (count($data101)) {
                        $spulist = array_merge($data2, $data101);
                    } else {
                        $spulist = $data2;
                    }
                }
                break;
            case 1:
                if ($branchid == TBranchInfo::MSHOP) {
                    $spulist = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                } else {
                    $data2 = TSpuShop::find()
                        ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    $data101 = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    //过滤掉101店铺的上架商品
                    foreach ($data101 as $key => $value) {
                        foreach ($data2 as $k => $v) {
                            if ($v['SpuId'] == $value['SpuId']) {
                                unset($data101[$key]);
                            }
                        }
                    }
                    if (count($data101)) {
                        $spulist = array_merge($data2, $data101);
                    } else {
                        $spulist = $data2;
                    }
                }
                break;
            case 2:
                if ($branchid == TBranchInfo::MSHOP) {
                    $spulist = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                } else {
                    $data2 = TSpuShop::find()
                        ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    $data101 = TSpuShop::find()
                        ->where(['BranchId' => TBranchInfo::MSHOP, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                        ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                        ->addParams([':SpuId' => "%$keyword%"])
                        ->addParams([':SpuName' => "%$keyword%"])
                        ->orderBy(' OnDate desc ')
                        ->asArray()->all();
                    //过滤掉101店铺的上架商品
                    foreach ($data101 as $key => $value) {
                        foreach ($data2 as $k => $v) {
                            if ($v['SpuId'] == $value['SpuId']) {
                                unset($data101[$key]);
                            }
                        }
                    }
                    if (count($data101)) {
                        $spulist = array_merge($data2, $data101);
                    } else {
                        $spulist = $data2;
                    }
                }
                break;
            case 3:
                $spulist = TSpuShop::find()
                    ->where(['BranchId' => $branchid, 'ShopStatus' => 1, 'SpuType' => TSpu::SPU_TYPE_RETAIL])
                    ->andWhere("SpuId like :SpuId or SpuName like :SpuName")
                    ->addParams([':SpuId' => "%$keyword%"])
                    ->addParams([':SpuName' => "%$keyword%"])
                    ->orderBy(' OnDate desc ')
                    ->asArray()->all();
                break;
            case 10:
                break;
            default :
                break;
        }
        return $spulist;
    }

    //上架商品的sku
    public static function upSku($params)
    {
        $spushop = TSpuShop::find()
            ->where(['SpuId' => $params['spuid'], 'BranchId' => $params['branchid']])
            ->one();
        if (isset($params['skuList'])) {
            $skus = [];
            $typeprice = 0;
            $skunumber = 0;
            foreach ($params['skuList'] as $key => $v) {
                $sku = TSku::find()
                    ->where(['SkuId' => $v, 'BranchId' => $params['branchid']])
                    ->asArray()->one();
                $arr = [];
                $arr['vector'] = json_decode($sku['SkuVector'], true);
                $arr['sku'] = $sku['SkuId'];
                $arr['price'] = $sku['SkuPrice'] * 100;
                $arr['type'] = $sku['SkuPriceType'];
                $skunumber += $sku['SkuNum'];
                $arr['count'] = $sku['SkuNum'];
                $skus[] = $arr;
                $typeprice += $arr['type'];
            }
            if ($skunumber <= 0) {
                return '未设置库存数据,请在商品编辑页面，设置库存数量';
            }
            $spushop->SpuVector = json_encode($skus, JSON_UNESCAPED_UNICODE);
        }
        $spushop->ShopStatus = 1;
        if ($typeprice > 0) {
            $spushop->SpuPriceType = 1;
        }
        if ($spushop->save()) {
            return 1;
        } else {
            return 2;
        }
    }

    //上架商品的图片上传
    public static function getImgUrl()
    {
        $type = explode('/', $_FILES['img']['type']);
        $mime = ['jpeg', 'png', 'gif'];
        $_FILES['img']['name'];
        if (!in_array($type['1'], $mime, true)) {
            return '请选择类型为jpeg、png、gif的图片';
        }
        $path = $_FILES['img']['tmp_name'];
        $bucket = 'picsissiok'; // 自定义空间名称，在http://console.qcloud.com/image/bucket创建
        $fileid = time() . rand(1000, 9999);  // 自定义文件名
        $uploadRet = ImageV2::upload($path, $bucket, $fileid);
        $imgs = $uploadRet['data']['downloadUrl'];
        return $imgs;
    }

    //上架商品信息（基本和详细）
    public static function upSpu($params, $branchid, $workerid)
    {
        $spuinfo = TSpu::findOne($params['spushopid']);
        $spu_shop = new TSpuShop();
        $spu_shop->SpuId = $spuinfo['SpuId'];
        $spu_shop->BranchId = $branchid == 0 ? 100 : $branchid;
        $spu_shop->SpuName = $spuinfo['SpuName'];
        $spu_shop->OnDate = date('Y-m-d H:i:s', time());

        $SpuShopShowPrice = static::getSpuShopShowPrice($branchid, $spuinfo['SpuId']);
        $spu_shop->SpuVector = $spuinfo['SpuVector'];
        $spu_shop->ShowPrice = $SpuShopShowPrice > 0 ? $SpuShopShowPrice : $spuinfo['SpuPrice'];
        $spu_shop->SpuVector = $spuinfo['SpuVector'];
        $spu_shop->CategoryId = $spuinfo['CategoryId'];
        $spu_shop->CategoryIdSub = $spuinfo['CategoryIdSub'];
        $spu_shop->CategoryIdTre = $spuinfo['CategoryIdTre'];
        $spu_shop->ImgUrl = json_encode($params['imgurl'], JSON_UNESCAPED_UNICODE);
        $spu_shop->SpuDetailType = $params['SpuDetailType'];
        if ($params['SpuDetailType'] == 0) {
            $spu_shop->SpuDetail = json_encode($params['spuimg'], JSON_UNESCAPED_UNICODE);
        } elseif ($params['SpuDetailType'] == 1) {
            $spu_shop->SpuDetail = $params['SpuDetail'];
        } elseif ($params['SpuDetailType'] == 2) {
            $spu_shop->SpuDetailHtml = $params['SpuDetail'];
        }
        $spu_shop->ExpressPrice = $params['ExpressPrice'] * 100;
        $spu_shop->SpuWeight = $params['SpuWeight'];
        $spu_shop->WorkerId = $workerid;
        $spu_shop->ShopStatus = 1;
        if (isset($params['packdetail'])) {
            $spu_shop->PackDetail = $params['packdetail'] ? $params['packdetail'] : '';
            $spu_shop->SpuType = 3;
        }
        $spu_shop->Period = $spuinfo['Period'];
        if ($spu_shop->save()) {
            return $spu_shop->primaryKey;
        } else {
            return 0;
        }
    }

    //获取上架商品的店铺列表
    public static function getBranch()
    {
        $data = TSpuShop::find()->groupBy('BranchId')->asArray()->all();
        $branchlist = [];
        foreach ($data as $key => $value) {
            $branch = TBranchInfo::findOne($value['BranchId']);
            $branchlist[] = ['BranchId' => $branch['BranchId'], 'BranchName' => $branch['BranchName']];
        }
        return $branchlist;
    }

    //下架商品
    public static function downSpu($spushopid)
    {
        $spushop = TSpuShop::findOne($spushopid);
        $spushop->ShopStatus = 0;
        $spushop->OffDate = date('Y-m-d H:i:s', time());
        if ($spushop->save()) {
            TPageList::deleteAll(['SpuId' => $spushop['SpuId'], 'BranchId' => $spushop['BranchId']]);
            return true;
        } else {
            return false;
        }
    }

    /**选择部分商品特价
     * @param $page 当前页数
     * @param $count 当前每页条数
     * @param $branchid 当前的选择的店铺
     * @param $upgood 选择全部上架商品
     * @return array
     */
    public static function selectSpulist($page, $count, $branchid, $upgood)
    {
        //$branch = explode(',', $branchid);
        $connection = Yii::$app->db; //连接
        if ($upgood) {
            $sql = "select a.SpuId, a.SpuName, a.CategoryId, a.CategoryIdSub, a.CategoryIdTre, sum(b.SkuNum) as num from 
t_spu_shop a,t_sku b where a.SpuId=b.SpuId and b.BranchId in ($branchid) and 
SkuNum > 0  group by  a.SpuId";
        } else {
            $sql = "select a.SpuId, a.SpuName, a.CategoryId, a.CategoryIdSub, a.CategoryIdTre, sum(b.SkuNum) as num from 
t_spu a,t_sku b where a.SpuId=b.SpuId and b.BranchId in ($branchid) and 
SkuNum > 0  group by  a.SpuId";
        }
        $command = $connection->createCommand($sql);
        $spulist = $command->queryAll();
        foreach ($spulist as $key => $spu) {
            //获取分类的名称
            $categoryname = TCategory::getCategoryName($spu['CategoryId'], $spu['CategoryIdSub'], $spu['CategoryIdTre']);
            $name = '';
            if ($categoryname) {
                foreach ($categoryname as $k => $v) {
                    $name .= $v['name'] . '-';
                }
                $name = trim($name, '-');
            } else {
                $name = '----';
            }
            $spulist[$key]['categoryname'] = $name;

        }
        //分页
        $pageData = [];
        if ($spulist) {
            //总页数
            $pagesall = ceil(count($spulist) / $count);
            if ($pagesall < 1) {
                $pagesall = 0;
            }
            if ($page <= 1) {
                $page = 1;
            }
            //当前分页
            if ($page >= $pagesall) {
                $page = $pagesall;
                $startIndex = ($page - 1) * $count;
                $endIndex = count($spulist);
            } else {
                $startIndex = ($page - 1) * $count;
                $endIndex = $startIndex + $count;
            }
            //每页的数据
            for ($n = $startIndex; $n < $endIndex; $n++) {
                if ($n < count($spulist)) {
                    $pageData[] = $spulist[$n];
                }
            }
        } else {
            $pagesall = 0;
            $page = 0;
        }
        $data = ['pages' => $pagesall, 'page' => $page, 'list' => $pageData];
        return $data;
    }

    //搜索部分商品列表接口
    public static function searchSelectSpu($page, $count, $branchid, $upgood, $keyword, $recordid, $begintime, $endtime, $begindate, $enddate, $timetype, $params)
    {
        $Monday = $params->get('monday');
        $Tuesday = $params->get('tuesday');
        $Wednesday = $params->get('wednesday');
        $Thursday = $params->get('thursday');
        $Friday = $params->get('friday');
        $Saturday = $params->get('saturday');
        $Sunday = $params->get('sunday');
        //价格特价
        $price = $params->get('rule_end') * 100;
        $PreferentialType = $params->get('type');
        $ac = TActivitySalesPromotion::findOne($recordid);
        $record_spu = $ac ? explode(',', $ac->SpuIdList) : [];
        $branchnum = count($branchid);
        $spuid = [];
        //周期性促销
        if ($timetype == 1) {
            //单个店铺
            if ($branchnum == 1) {
                if ($branchid[0] == TBranchInfo::MSHOP) {
                    $spuid = self::branchSpu([0, TBranchInfo::MSHOP], $Monday, $Tuesday, $Wednesday, $Thursday, $Friday, $Saturday, $Sunday, $begintime, $endtime);
                } else {
                    $spuid = self::branchSpu($branchid, $Monday, $Tuesday, $Wednesday, $Thursday, $Friday, $Saturday, $Sunday, $begintime, $endtime);
                }
            }
            //多个店铺
            if ($branchnum > 1) {
                foreach ($branchid as $k => $v) {
                    $spuid = self::likeBranchSpu($branchid, $Monday, $Tuesday, $Wednesday, $Thursday, $Friday, $Saturday, $Sunday, $begintime, $endtime);
                }
            }
        } else {//临时性促销
            //单个店铺
            if ($branchnum == 1) {
                if ($branchid[0] == TBranchInfo::MSHOP) {
                    //促销做判断
                    $actives = TActivitySalesPromotion::find()
                        ->where(['ActivityBranchIdList' => [0, TBranchInfo::MSHOP], 'BranchStatus' => [TActivitySalesPromotion::Branch_All, TActivitySalesPromotion::Branch_Online]])
                        ->andWhere("ActivityStatus = 0 and ActivityEndTime > '$begintime' and ActivityBeginTime < '$endtime' and '$begindate' <= ActivityEndDate and '$enddate' >= ActivityBeginDate ")
                        ->all();
                } else {
                    //促销做判断
                    $actives = TActivitySalesPromotion::find()
                        ->where(['ActivityBranchIdList' => $branchid, 'BranchStatus' => [TActivitySalesPromotion::Branch_Only, TActivitySalesPromotion::Branch_Online]])
                        ->andWhere("ActivityStatus = 0 and ActivityEndTime > '$begintime' and ActivityBeginTime < '$endtime' and '$begindate' <= ActivityEndDate and '$enddate' >= ActivityBeginDate ")
                        ->all();
                }
                if ($actives) {
                    foreach ($actives as $active) {
                        $spuid = array_merge($spuid, $active->getSpuArray());
                    }
                }
            }
            //多个店铺
            if ($branchnum > 1) {
                foreach ($branchid as $k => $v) {
                    $actives = TActivitySalesPromotion::find()
                        ->where(['BranchStatus' => TActivitySalesPromotion::Branch_More])
                        ->andWhere(['like', 'ActivityBranchIdList', $v])
                        ->andWhere("ActivityStatus = 0 and ActivityEndTime > '$begintime' and ActivityBeginTime < '$endtime'  and '$begindate' < ActivityEndDate and '$enddate' > ActivityBeginDate ")
                        ->all();
                    if ($actives) {
                        foreach ($actives as $active) {
                            $spuid = array_merge($spuid, $active->getSpuArray());
                        }
                    }
                }
            }
        }
        //过滤掉特价商品
        $spupricetype = TSpuShop::find()->where(['SpuPriceType' => 1, 'BranchId' => $branchid])->all();
        if ($spupricetype) {
            foreach ($spupricetype as $spushop) {
                $spuid[] = $spushop->SpuId;
            }
        }
        $spuid = array_unique($spuid);
        $branchid = implode(',', $branchid);
        $connection = Yii::$app->db; //连接
        //如果特价促销有服务型商品
        if ($PreferentialType == 4) {
            if ($upgood) {
                $sql = "select a.SpuId, a.SpuName, a.CategoryId, a.CategoryIdSub, a.CategoryIdTre, a.ShowPrice, sum(b.SkuNum) as num from 
t_spu_shop a,t_sku b where a.SpuId=b.SpuId and a.ShopStatus=1 and a.SpuPriceType = 0 and a.SpuType in (1,2) and b.BranchId in ($branchid,101) and (a.SpuId like '%$keyword%' or a.SpuName like '%$keyword%')  group by  a.SpuId";
            } else {
                $sql = "select a.SpuId, a.SpuName, a.CategoryId, a.CategoryIdSub, a.CategoryIdTre, a.ShowPrice, sum(b.SkuNum) as num from
 t_spu_shop a,t_sku b where a.SpuId=b.SpuId and a.SpuPriceType = 0 and a.SpuType in (1,2) and b.BranchId in ($branchid) and (a.SpuId like '%$keyword%' or a.SpuName like '%$keyword%') group by  a.SpuId";
            }
        } else {
            if ($upgood) {
                $sql = "select a.SpuId, a.SpuName, a.CategoryId, a.CategoryIdSub, a.CategoryIdTre, a.ShowPrice, sum(b.SkuNum) as num from 
t_spu_shop a,t_sku b where a.SpuId=b.SpuId and a.ShopStatus = 1 and a.SpuPriceType = 0 and a.SpuType = 1 and b.BranchId in ($branchid,101) and (a.SpuId like '%$keyword%' or a.SpuName like '%$keyword%')  group by  a.SpuId";
            } else {
                $sql = "select a.SpuId, a.SpuName, a.CategoryId, a.CategoryIdSub, a.CategoryIdTre, a.ShowPrice, sum(b.SkuNum) as num from
 t_spu_shop a,t_sku b where a.SpuId=b.SpuId and a.SpuPriceType = 0 and a.SpuType = 1 and b.BranchId in ($branchid) and (a.SpuId like '%$keyword%' or a.SpuName like '%$keyword%') group by  a.SpuId";
            }
        }
        $command = $connection->createCommand($sql);
        $spulist = $command->queryAll();
        foreach ($spulist as $key => $spu) {
            //获取分类的名称
            $categoryname = TCategory::getCategoryName($spu['CategoryId'], $spu['CategoryIdSub'], $spu['CategoryIdTre']);
            $name = '';
            if ($categoryname) {
                foreach ($categoryname as $k => $v) {
                    $name .= $v['name'] . '-';
                }
                $name = trim($name, '-');
            } else {
                $name = '----';
            }
            $spulist[$key]['categoryname'] = $name;
            foreach ($spuid as $k => $v) {
                if (($v == $spu['SpuId']) && !in_array($spu['SpuId'], $record_spu)) {
                    unset($spulist[$key]);
                }
            }
            if ($PreferentialType == 4 && $spu['ShowPrice'] < $price) {
                unset($spulist[$key]);
            }
        }
        ArrayHelper::multisort($spulist, 'SpuId');
        //分页
        $pageData = [];
        if ($spulist) {
            //总页数
            $pagesall = ceil(count($spulist) / $count);
            if ($pagesall < 1) {
                $pagesall = 0;
            }
            if ($page <= 1) {
                $page = 1;
            }
            //当前分页
            if ($page >= $pagesall) {
                $page = $pagesall;
                $startIndex = ($page - 1) * $count;
                $endIndex = count($spulist);
            } else {
                $startIndex = ($page - 1) * $count;
                $endIndex = $startIndex + $count;
            }
            //每页的数据
            for ($n = $startIndex; $n < $endIndex; $n++) {
                if ($n < count($spulist)) {
                    $pageData[] = $spulist[$n];
                }
            }
        } else {
            $pagesall = 0;
            $page = 0;
        }
        $data = ['pages' => $pagesall, 'page' => $page, 'list' => $pageData];
        return $data;
    }

    //通过星期过滤商品
    public static function checkDay($branchid, $begintime, $endtime, $day, $week)
    {
        //促销做判断
        $actives = TActivitySalesPromotion::find()
            ->where(['ActivityBranchIdList' => $branchid, 'BranchStatus' => [TActivitySalesPromotion::Branch_Only, TActivitySalesPromotion::Branch_Online]])
            ->andWhere("ActivityStatus = 0 and ActivityEndTime >= '$begintime' and ActivityBeginTime <= '$endtime' and $week = $day")
            ->all();
        return $actives;
    }

    public static function checkDayBranchs($branchid, $begintime, $endtime, $day, $week)
    {
        //促销做判断
        $actives = TActivitySalesPromotion::find()
            ->where(['BranchStatus' => [TActivitySalesPromotion::Branch_More]])
            ->andWhere(['like', 'ActivityBranchIdList', $branchid])
            ->andWhere("ActivityStatus = 0 and ActivityEndTime >= '$begintime' and ActivityBeginTime <= '$endtime' and $week = $day")
            ->all();
        return $actives;
    }

    //获取多个店铺的时候促销的商品
    public static function likeBranchSpu($branchid, $Monday, $Tuesday, $Wednesday, $Thursday, $Friday, $Saturday, $Sunday, $begintime, $endtime)
    {
        $spuid = [];
        if ($Monday) {
            $actives = self::checkDayBranchs($branchid, $begintime, $endtime, $Monday, 'Monday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Tuesday) {
            $actives = self::checkDayBranchs($branchid, $begintime, $endtime, $Tuesday, 'Tuesday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Wednesday) {
            $actives = self::checkDayBranchs($branchid, $begintime, $endtime, $Wednesday, 'Wednesday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Thursday) {
            $actives = self::checkDayBranchs($branchid, $begintime, $endtime, $Thursday, 'Thursday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Friday) {
            $actives = self::checkDayBranchs($branchid, $begintime, $endtime, $Friday, 'Friday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Saturday) {
            $actives = self::checkDayBranchs($branchid, $begintime, $endtime, $Saturday, 'Saturday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Sunday) {
            $actives = self::checkDayBranchs($branchid, $begintime, $endtime, $Sunday, 'Sunday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        return $spuid;
    }

    //传不同店铺获取促销的商品
    public static function branchSpu($branchid, $Monday, $Tuesday, $Wednesday, $Thursday, $Friday, $Saturday, $Sunday, $begintime, $endtime)
    {
        $spuid = [];
        if ($Monday) {
            $actives = self::checkDay($branchid, $begintime, $endtime, $Monday, 'Monday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Tuesday) {
            $actives = self::checkDay($branchid, $begintime, $endtime, $Tuesday, 'Tuesday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Wednesday) {
            $actives = self::checkDay($branchid, $begintime, $endtime, $Wednesday, 'Wednesday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Thursday) {
            $actives = self::checkDay($branchid, $begintime, $endtime, $Thursday, 'Thursday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Friday) {
            $actives = self::checkDay($branchid, $begintime, $endtime, $Friday, 'Friday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Saturday) {
            $actives = self::checkDay($branchid, $begintime, $endtime, $Saturday, 'Saturday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        if ($Sunday) {
            $actives = self::checkDay($branchid, $begintime, $endtime, $Sunday, 'Sunday');
            if ($actives) {
                foreach ($actives as $active) {
                    $spuid = array_merge($spuid, $active->getSpuArray());
                }
            }
        }
        return $spuid;
    }

    //促销活动详情查看商品列表接口
    public static function searchSelectSpuLook($page, $count, $branchid, $upgood, $keyword, $spuid)
    {
        foreach ($spuid as $k => $v) {
            $spuid[$k] = (string)$v;
        }
        $branch = array_merge($branchid, ['101']);
        if ($upgood) {
            $spulist = TSpuShop::find()->select('t_sku.SpuId, t_sku.BranchId, t_spu_shop.SpuName, t_spu_shop.CategoryId, t_spu_shop.CategoryIdSub, t_spu_shop.CategoryIdTre, sum(t_sku.SkuNum) as num')
                ->leftJoin('t_sku', 't_sku.SpuId = t_spu_shop.SpuId')
                ->where(['t_spu_shop.BranchId' => $branch, 't_spu_shop.SpuId' => $spuid, 'ShopStatus' => 1])
                ->andWhere("t_spu_shop.SpuId like '%$keyword%' or t_spu_shop.SpuName like '%$keyword%' ")
                ->groupBy('t_spu_shop.SpuId')
                ->asArray()->all();
        } else {
            $spulist = TSpuShop::find()->select('t_sku.SpuId, t_sku.BranchId, t_spu_shop.SpuName, t_spu_shop.CategoryId, t_spu_shop.CategoryIdSub, t_spu_shop.CategoryIdTre, sum(t_sku.SkuNum) as num')
                ->leftJoin('t_sku', 't_sku.SpuId = t_spu_shop.SpuId')
                ->where(['t_spu_shop.BranchId' => $branch, 't_sku.SpuId' => $spuid])
                ->andWhere("t_sku.SpuId like '%$keyword%' or t_spu_shop.SpuName like '%$keyword%' ")
                ->groupBy('t_sku.SpuId')
                ->asArray()->all();
        }
        //数据库查询方式
//        $connection = Yii::$app->db; //连接
//        if($upgood){
//            $sql = "select a.SpuId, a.SpuName, a.CategoryId, a.CategoryIdSub, a.CategoryIdTre, sum(b.SkuNum) as num from
//t_spu_shop a,t_sku b where a.SpuId=b.SpuId and b.BranchId in ($branchid,101) and a.SpuId in ($spuid) and (a.SpuId like '%$keyword%' or a.SpuName like '%$keyword%')  group by  a.SpuId";
//        } else {
//            $sql = "select a.SpuId, a.SpuName, a.CategoryId, a.CategoryIdSub, a.CategoryIdTre, sum(b.SkuNum) as num from
// t_spu a,t_sku b where a.SpuId=b.SpuId and b.BranchId in ($branchid,0) and a.SpuId in ($spuid) and (a.SpuId like '%$keyword%' or a.SpuName like '%$keyword%') group by  a.SpuId";
//        }
//        $command = $connection->createCommand($sql);
//        $spulist = $command->queryAll();

        foreach ($spulist as $key => $spu) {
            //获取分类的名称
            $categoryname = TCategory::getCategoryName($spu['CategoryId'], $spu['CategoryIdSub'], $spu['CategoryIdTre']);
            $name = '';
            if ($categoryname) {
                foreach ($categoryname as $k => $v) {
                    $name .= $v['name'] . '-';
                }
                $name = trim($name, '-');
            } else {
                $name = '----';
            }
            $spulist[$key]['categoryname'] = $name;
        }
        //分页
        $pageData = [];
        if ($spulist) {
            //总页数
            $pagesall = ceil(count($spulist) / $count);
            if ($pagesall < 1) {
                $pagesall = 0;
            }
            if ($page <= 1) {
                $page = 1;
            }
            //当前分页
            if ($page >= $pagesall) {
                $page = $pagesall;
                $startIndex = ($page - 1) * $count;
                $endIndex = count($spulist);
            } else {
                $startIndex = ($page - 1) * $count;
                $endIndex = $startIndex + $count;
            }
            //每页的数据
            for ($n = $startIndex; $n < $endIndex; $n++) {
                if ($n < count($spulist)) {
                    $pageData[] = $spulist[$n];
                }
            }
        } else {
            $pagesall = 0;
            $page = 0;
        }
        $data = ['pages' => $pagesall, 'page' => $page, 'list' => $pageData];
        return $data;
    }

    //获取单个商品符合的促销
    public static function getSkuForActive($skuId, $branch)
    {
        $skuId = (string)$skuId;
        $sku = TSku::find()->where(['SkuId' => $skuId, 'BranchId' => $branch->BranchId])->with('spu')->one();
        if (!$sku) {
            $sku = TSku::find()->where(['SkuId' => $skuId, 'BranchId' => TBranchInfo::MSHOP])->with('spu')->one();
        }
        $spu_active = [];
        $activity = null;
        if ($sku && $sku->spu) {
            $activity = TActivitySalesPromotion::getActivityForSpu($sku->spu, $branch->BranchId, TActivitySalesPromotion::range_online);
        } elseif ($sku && $sku->spunew) {
            $activity = TActivitySalesPromotion::getActivityForSpu($sku->spunew, $branch->BranchId, TActivitySalesPromotion::range_online);
        }
        if ($activity) {
            $spu_active[$activity['RecordId']][] = $sku;
        } else {
            $spu_active[0][] = $sku;
        }
        return $spu_active;
    }

    /**
     * 判断spu是否有库存
     * @param $spuId string Spu的id
     * @param $branchId int 店铺id
     * @return bool
     */
    public static function spuHasStock($spuId, $branchId)
    {
        $conditions = [
            'BranchId' => [$branchId, TBranchInfo::MSHOP],
            'SpuId' => $spuId
        ];
        return TSku::find()->select('SUM(SkuNum)')->where($conditions)->scalar() > 0;
    }

    /**
     * 获取上架的商品列表
     * @param int $branchId 店铺的id
     * @param int $page
     * @param int $pageSize
     * @param null|string $keyword 搜索关键字
     * @param null|array $additionalParams 附加参数数组
     * @return array|null
     * @internal param int $pageBeg
     */
    public static function getOnShelfSpuList($branchId, $page = 1, $pageSize = 10, $keyword = null, $additionalParams = null)
    {
        // 上架的Spu
        $conditions = [
            'BranchId' => [$branchId, TBranchInfo::MSHOP], 'ShopStatus' => self::STATUS_ONLINE
        ];

        $query = TSpuShop::find()->where($conditions);
        if ($keyword != null) {
            $query = $query->andWhere('SpuName like :keyword OR SpuId like :keyword')->addParams([':keyword' => "%$keyword%"]);
        }

        $spuList = $query->asArray()->all();
        if ($spuList == null) {
            return null;
        }

        $filterSpuIds = null;
        if ($additionalParams && isset($additionalParams['filter_spu_ids'])) {
            $filterSpuIds = $additionalParams['filter_spu_ids'];
        }

        $spuListUnique = [];
        $spuIds = [];
        foreach ($spuList as $spu) {
            if (!isset($spuListUnique[$spu['SpuId']]) && ($filterSpuIds === null || !in_array($spu['SpuId'], $filterSpuIds))
            ) {
                $spuListUnique[$spu['SpuId']] = $spu;
                $spuIds[] = strval($spu['SpuId']);
            } else if ($spu['BranchId'] != TBranchInfo::MSHOP) {
                $spuListUnique[$spu['SpuId']] = $spu;
            }
        }

        $conditions = [
            'SpuId' => $spuIds, 'BranchId' => [$branchId, TBranchInfo::MSHOP]
        ];
        // SKU的库存和最低的价格
        $skuInfos = TSku::find()->select(['SkuSum' => 'SUM(SkuNum)', 'SpuShowPrice' => 'MIN(SkuPrice)', 'SpuId'])->where($conditions)
            ->groupBy(['SpuId'])->indexBy('SpuId')->asArray()->all();
//        $sql = 'SELECT SUM(SkuNum) AS SkuSum, MIN(SkuPrice) AS SpuShowPrice, SpuId FROM ' . TSku::tableName()
//            . ' WHERE SpuId IN (\'' . implode('\',\'', $spuIds) . "') AND BranchId=$branchId "
//            . ' GROUP BY SpuId';
//        $skuInfos = Yii::$app->db->createCommand($sql)->queryAll();
//        $skuInfos = array_combine(array_column($skuInfos, 'SpuId'), $skuInfos);
        $spuData = [];
        foreach ($spuListUnique as $spuId => $spu) {
            if (isset($skuInfos[$spu['SpuId']]) && isset($skuInfos[$spu['SpuId']]['SkuSum']) && $skuInfos[$spu['SpuId']]['SkuSum'] > 0) {
                // 库存大于0
                $spu['SpuShowPrice'] = $skuInfos[$spu['SpuId']]['SpuShowPrice'];
//                $spu['SkuSum'] = $skuInfos[$spu['SpuId']]['SkuSum'];
                $spuData[] = $spu;
            }
        }

        $pages = ceil(count($spuData) / $pageSize);
        if ($pages < 1) {
            $pages = 1;
        }
        if ($page >= $pages) {
            $page = $pages;
            $startIndex = ($page - 1) * $pageSize;
            $endIndex = count($spuData);
        } else {
            $startIndex = ($page - 1) * $pageSize;
            $endIndex = $startIndex + $pageSize;
        }
        $spuData = array_slice($spuData, $startIndex, $endIndex);
        foreach ($spuData as &$spu) {
            $spu['ImgUrl'] = json_decode($spu['ImgUrl'], true);
        }
        $spuData = ['list' => $spuData];
        $spuData['page'] = $page;
        $spuData['pages'] = $pages;
        return $spuData;
    }

    /**
     * 获取在$branchId有库存，并且在$branchId店铺或微商城上架的商品的信息
     * @param $spuId string Spu的id
     * @param $branchId int 店铺id
     * @return array|null
     */
    public static function getOnShelfSpuInfo($spuId, $branchId)
    {
        if (!static::spuHasStock($spuId, $branchId)) {
            // 如果没有库存，无需再看是否上架
            return null;
        }
        $conditions = [
            'BranchId' => [$branchId, TBranchInfo::MSHOP], 'SpuId' => $spuId, 'ShopStatus' => self::STATUS_ONLINE
        ];
        $spuShops = TSpuShop::find()->where($conditions)->all();
        if ($spuShops == null) {
            // 未上架
            return null;
        }
        $spuShop = $spuShops[0];
        if (count($spuShops) > 1) {
            // 在$branchId店铺和微商城都有上架
            if ($spuShops[0]->BranchId == TBranchInfo::MSHOP) {
                $spuShop = $spuShops[1];
            }
        }

        $spuInfo = [
            'SpuId' => $spuShop->SpuId,
            'SpuName' => $spuShop->SpuName,
            'ImgUrl' => json_decode($spuShop->ImgUrl, true),
            'ShowPrice' => self::getSpuShopShowPrice($branchId, $spuId)
        ];

        return $spuInfo;
    }

    /**
     * 带筛选功能的spushop选择列表
     * @param array $branchids
     * @param string $keyword
     * @param array $condition
     * @return array
     * @throws \yii\base\InvalidParamException
     */
    public static function spusOfFilter(array $branchids = [], $keyword = '', array $condition = [])
    {
        $fields = ['SpuShopId', 'SpuId', 'BranchId', 'SpuName', 'ShowPrice', 'ImgUrl', 'SpuType'];
        $spus = self::find()->select($fields)->where(['ShopStatus' => ConstantModel::ON_SPU, 'BranchId' => $branchids]);
        if ($keyword !== '') {
            $spus = $spus->andWhere(['like', 'SpuName', $keyword]);
        }
        $spus = $spus->asArray()->all();
        if ($condition) {
            $spus = ToolsModel::filterData($condition, $spus);
        }
        $spus = array_map(function ($var) {
            $var['ImgUrl'] = $var['ImgUrl'] ? ArrayHelper::getValue(json_decode($var['ImgUrl'], true), 0, '') : '';
            return $var;
        }, $spus);
        $pageSize = ArrayHelper::getValue(Yii::$app->request->get(), 'pageSize', ConstantModel::PAGE_SIZE_DEFAULT);
        $pages = ceil(count($spus) / $pageSize);
        $paginaction = ToolsModel::paginaction($pages, $pageSize);

        return [
            'page' => $paginaction['page'],
            'pages' => $pages,
            'list' => array_slice($spus, $paginaction['offset'], $pageSize)
        ];
    }

    /**
     * 获取圈子的Spu列表 废弃
     * @param  string $branchId 店铺ID
     * @param  integer $page 分页页码
     * @param  integer $pageSize 每一页的条目数量
     * @param  string $keyword 搜索关键字，可以为空
     * @return Spu列表
     */
    public static function getOnShelfSpuListForCircle($branchId, $keyword = null, $page = 1, $pageSize = 10)
    {
        // 上架的Spu
        $conditions = [
            'BranchId' => [$branchId, TBranchInfo::MSHOP], 'ShopStatus' => self::STATUS_ONLINE
        ];

        $query = TSpuShop::find()->where($conditions);
        if ($keyword != null) {
            $query = $query->andWhere('SpuName like :SpuName')->addParams([':SpuName' => "%$keyword%"]);
        }

        $spuList = $query->asArray()->all();
        if ($spuList == null) {
            return null;
        }

        $spuListUnique = [];
        $spuIds = [];
        foreach ($spuList as $spu) {
            if (!isset($spuListUnique[$spu['SpuId']])) {
                $spuListUnique[$spu['SpuId']] = $spu;
                $spuIds[] = strval($spu['SpuId']);
            } else if ($spu['BranchId'] != TBranchInfo::MSHOP) {
                $spuListUnique[$spu['SpuId']] = $spu;
            }
        }

        $spuData = array_values($spuListUnique);

        $pages = ceil(count($spuData) / $pageSize);
        if ($pages < 1) {
            $pages = 1;
        }
        if ($page >= $pages) {
            $page = $pages;
            $startIndex = ($page - 1) * $pageSize;
            $endIndex = count($spuData);
        } else {
            $startIndex = ($page - 1) * $pageSize;
            $endIndex = $startIndex + $pageSize;
        }
        $spuData = array_slice($spuData, $startIndex, $endIndex);
        $spuList = [];
        foreach ($spuData as &$spu) {
            $spu['ImgUrl'] = json_decode($spu['ImgUrl'], true);
            if (!empty($spu['ImgUrl'])) {
                $spu['ImgUrl'] = $spu['ImgUrl'][0];
            }
            $spuList[] = [
                'SpuId' => $spu['SpuId'],
                'SpuName' => $spu['SpuName'],
                'ImgUrl' => $spu['ImgUrl'],
                'ShowPrice' => $spu['ShowPrice'],
            ];
        }
        return $spuList;
    }

    /**
     * 获取$branchIds店铺上架的，spuId为$spuId的Spu
     * @param array|int $branchIds 店铺Id
     * @return array
     */
    public static function findUpSpus($branchIds, $spuId = null, $asArray = false)
    {
        $retSpus = static::findUpSpusIndexed($branchIds, $spuId, $asArray);
        $retSpus = array_values($retSpus);
        return $retSpus;
    }

    public static function findUpSpusIndexed($branchIds, $spuId = null, $asArray = false)
    {
        $query = self::find()->where(
            [
                'ShopStatus' => TSpuShop::STATUS_ONLINE
            ]
        );
        if ($branchIds != null) {
            $query = $query->andWhere([
                'BranchId' => $branchIds,
            ]);
        }
        if ($spuId !== null) {
            $query = $query->andWhere(['SpuId' => $spuId]);
        }
        if ($asArray) {
            $query = $query->asArray();
        }

        $spus = $query->orderBy(['SpuWeight' => SORT_DESC])->all();
        $retSpus = [];
        foreach ($spus as $spu) {
            if (!isset($retSpus[$spu['SpuId']]) || $retSpus[$spu['SpuId']]['BranchId'] == TBranchInfo::MSHOP) {
                $retSpus[$spu['SpuId']] = $spu;
            }
        }
        return $retSpus;
    }

    public function getPriceRule()
    {
        return TConfig::getPriceRule()['ConfigValue'];
    }

    public static function findSpuInfo($item_no,$branchId) {
        $spuInfo = self::find()
            ->where(['SpuId' => $item_no,'BranchId'=>$branchId])
            ->one();
        return $spuInfo;
    }
}
